import subprocess
import re
import sys 


class Strace:
    """
    利用strace获取进程输出
    """
    def strace(self, pid, size=3000):
        cmd = ["strace", "-p", str(pid), "-ewrite", "-s", str(size)]
        process = subprocess.Popen(cmd,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE)
        while process.poll() is None:
            output = process.stderr.readline(size)
            self.format_trace(output)

    @staticmethod
    def format_trace(output):
        try:
            block = re.search(b"write\(\d+,\s+\"(.*)\\\\n", output).group(1).replace(b"\\\\", b"\\")
            text = eval(b''.join([b'b"', block, b'".decode()']))
            sys.stdout.write(text+"\n")
            sys.stdout.flush()
        except:
            pass
